package com.foreveross.push.nodeclient;

import java.io.IOException;
import java.nio.ByteBuffer;

import org.msgpack.MessagePack;
import org.msgpack.type.Value;

import com.google.gson.Gson;

/** 
 * @author 黄黎  
 * @version 创建时间：2014年5月19日 下午1:32:55 
 * 类说明 
 */
public class PackageUtil {
	public static <T> byte[] ToByteNoJson(T t){
 		byte[] b;
		try { 
			b = new MessagePack().write(t);
			byte[] len = ByteBuffer.allocate(4).putInt(b.length).array();
			byte[] msgHeartbeat= new byte[b.length + 5];
			for (int i = 0; i < msgHeartbeat.length; i++) {
				if(i<4)msgHeartbeat[i]=len[i];
				if(i==4)msgHeartbeat[i]=1;
				if(i>4)msgHeartbeat[i]=b[i-5];
			} 
			return msgHeartbeat;
		} catch (IOException e) { 
			e.printStackTrace();
		}
		return null;
 	}
	
	public static <T> byte[] ToByte(T t){
 		byte[] b;
		try {
			Gson gson=new Gson();
			String json=gson.toJson(t);
			b = new MessagePack().write(json);
			byte[] len = ByteBuffer.allocate(4).putInt(b.length).array();
			byte[] msgHeartbeat= new byte[b.length + 5];
			for (int i = 0; i < msgHeartbeat.length; i++) {
				if(i<4)msgHeartbeat[i]=len[i];
				if(i==4)msgHeartbeat[i]=1;
				if(i>4)msgHeartbeat[i]=b[i-5];
			} 
			return msgHeartbeat;
		} catch (IOException e) { 
			e.printStackTrace();
		}
		return null;
 	}

	public static Value byteToObject(byte[] btyes){
		   int len=0; 
		   byte[] lens=new byte[4];
		   for (int i = 0; i < 4; i++) {
			   lens[i]=btyes[i];
		   }
		   len=byteArrayToInt(lens);
		   byte[] conts=new byte[len];
		   for (int i = 0; i < conts.length; i++) {
			conts[i]=btyes[i+5];
		   }
		   MessagePack mPack=new MessagePack();
		   try {
			Value v= mPack.read(conts);
			
			return v;
		   } catch (IOException e) {
		   }
		   return null;
	   }
	
	   private static int byteArrayToInt(byte[] bytes) {
		                  int value= 0;
		                  for (int i = 0; i < 4; i++) {
		                      int shift= (4 - 1 - i) * 8;
		                      value +=(bytes[i] & 0x000000FF) << shift;
		                  }
		                  return value;
		            }

}
